package com.briup.jdbc.handler.invoke;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

import com.briup.jdbc.conn.JDBCPool;
import com.briup.jdbc.execute.DeleteExecute;
import com.briup.jdbc.execute.SelectExecute;
import com.briup.jdbc.execute.UpdateExecute;
import com.briup.jdbc.extannotation.ExtUpdate;
import com.briup.jdbc.interfaces.IInvoke;
import com.briup.jdbc.utils.AnalyseUtil;

public class UpdateInvoke extends AbstractInvoke implements IInvoke {

	public UpdateInvoke(Connection conn, boolean autoCommit) throws Exception {
		super(conn, autoCommit);
		// TODO Auto-generated constructor stub
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
		ExtUpdate extUpdate = method.getAnnotation(ExtUpdate.class);
		// 以K-V形式存放条件字段和值
		Map<String, Object> requiresMap = null;
		String sql = extUpdate.value();
		// 解析返回值类型
		Class<?> packType = int.class;
		// 解析条件字段
		if (sql.contains("#{")) {
			// 存放sql中条件中的字段名
			List<String> requireAttrNames = AnalyseUtil.analyseRequireSql(sql);
			// 获取方法中的参数
			Parameter[] parameters = method.getParameters();
			if (parameters == null || parameters.length == 0) {
				throw new Exception("parameters is null!");
			}
			// 请求属性替换
			requiresMap = AnalyseUtil.replaceRequireParams(requireAttrNames, method, sql, args);
			sql = AnalyseUtil.SQLReplaceAll(sql, requireAttrNames);
		}
		// 调用执行器
		Object obj = null;
		try {
			if (requiresMap == null) {
				obj = new UpdateExecute(sql, packType).update(conn);
			} else {
				obj = new UpdateExecute(sql, packType, requiresMap.values().toArray()).update(conn);
			}
			if (autoCommit) {
				JDBCPool.commit(conn);
				System.out.println(">>>>update>>>自动提交>>>");
			}
		} catch (Exception e) {
			if (autoCommit) {
				JDBCPool.rollback(conn);
				System.out.println(">>>>update>>>自动回滚>>>");
				e.printStackTrace();
			} else {
				throw e;
			}
		} finally {
			if (autoCommit) {
				JDBCPool.close(conn);
				System.out.println(">>>>update>>>自动关闭>>>");
			}
		}
		return obj;
	}

}
